/*
 * Created by SharpDevelop.
 * User: Oscar
 * Date: 29/09/2007
 * Time: 05:46 p.m.
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Xml;
using System.Configuration;
using System.Web;

namespace DemoPress.UrlRewriting
{
	/// <summary>
	/// Implements IConfigurationSectionHandler in order to handle web.config settings in demopress. The Create method
	/// will be called with a urlRewriting section in the web.config file.
	/// </summary>
	public class UrlRewriteSectionHandler : IConfigurationSectionHandler
	{
		private bool _rewriteOn;
		private UrlRewriteRule[] _rules;
		private string _rewriteBase;
		
		public string RewriteBase {
			get { return _rewriteBase; }
		}
		
		public bool RewriteOn {
			get { return _rewriteOn; }
		}
		
		public UrlRewriteRule[] Rules {
			get { return _rules; }
		}
		
		public object Create(object parent, object configContext, System.Xml.XmlNode section)
		{
			if(configContext == null)
			{
				throw new ArgumentNullException("configContext", "The configContext object provided is null");
			}
			if(section == null)
			{
				throw new ArgumentNullException("section", "The RewriteModule section Node is null and can not be processed.");
			}
			if(section.SelectSingleNode("rewriteOn") == null)
			{
				throw new ArgumentException("The RewriteModule section Node has no rewriteOn attribute.", "section");
			}
			string rewriteValue = section.SelectSingleNode("rewriteOn").InnerText;
			if(String.IsNullOrEmpty(rewriteValue))
			{
				throw new ArgumentException("The RewriteModule section Node has no value in rewriteOn attribute.", "section");
			}
			try
			{
				_rewriteOn = Boolean.Parse(rewriteValue);
			}
			catch (ArgumentNullException ane)
			{
				throw new ArgumentException("The RewriteModule section Node has no valid value in rewriteOn attribute.", "section", ane);
			}
			BuildRules(section.SelectSingleNode("rewriteRules"));
			_rewriteBase = HttpContext.Current.Request.ApplicationPath + "/";
			return this;
		}
		
		private void BuildRules(XmlNode rulesNode)
		{
			if(rulesNode == null)
			{
				return;
			}
			XmlNodeList list = rulesNode.SelectNodes("rule");
			_rules = new UrlRewriteRule[list.Count];
			if(list.Count == 0)
			{
				return;
			}
			XmlNode node;
			XmlAttribute source;
			XmlAttribute destination;
			
			for(int i=0; i<list.Count; i++)
			{
				node = list[i];
				source = node.Attributes["source"];
				if(source == null)
				{
					throw new ArgumentException("There is a rule Node with no source attribute.","rulesNode");
				}
				destination = node.Attributes["destination"];
				if(destination == null)
				{
					throw new ArgumentException("There is a rule Node with no destination attribute.","rulesNode");
				}
				_rules[i] = new UrlRewriteRule(source.InnerText, destination.InnerText, this);
			}
		}
	}
}
